//加载audio
var myAudio = new audio();

//游戏最开始的定义
var canvas = document.getElementById("myGame");
var game = new Niubi(800, 600, canvas, { preload: preload, create: create, update: update, render: render });

//游戏资源（如图片）的加载
function preload() {
    game.loadImage("flag", "./img/flag.png");
    var i = 0;
    for(; i < 3; i++){
        game.loadImage("ninja", "./img/man/ninja_" + i + ".png");
        game.loadImage("worm", "./img/worm/worm_" + i + ".png");
    }
}

var man;
var worm;
var flag;
var road = [];
game.init();
game.start();

//场景、角色等的创建
function create() {
    worm = game.addSprite(100, 200, "worm", 65, 90);
    worm.movement = true;

    flag = game.addSprite(100, 200, "flag", 97, 135);

    man = game.addSprite(0, 400, "ninja", 70, 100);

    var currentX = 0, currentY = 470;
    for(var i = 0; i < 10; i++){
        var oobj = {
            color: "black",
            width: utils.getRandom(70,500),
            height: 600,
            marginRight: utils.getRandom(100,250)
        };
        if(i != 0) currentY = utils.getRandom(350, 520);
        if(i == 5) oobj.width = 500;
        if(i == 8) oobj.marginRight = 250;
        if(i == 9) oobj.width = 400;
        road[i] = game.addBuilding(currentX, currentY, oobj, function(ctx){
            ctx.save();
            ctx.beginPath();
            ctx.fillStyle = this.color;/*设置填充颜色*/
            ctx.strokeStyle = this.color;
            ctx.fill();
            ctx.fillRect(this.x, this.y, this.w, this.h);/*绘制一个矩形，前两个参数决定开始位置，后两个分别是矩形的宽和高*/
            ctx.closePath();/*可选步骤，关闭绘制的路径*/
            ctx.stroke();
            ctx.restore();
        });
        currentX += oobj.width + oobj.marginRight;
    }
    worm.x = road[5].x + road[5].w *.8;
    worm.y = road[5].y - worm.h;
    flag.y = road[9].y - flag.h;
}

function update () {
    //game.addSprite(200, 100, "imgBird");
}
function forEach(func){
    for(var i = 0; i< 10; i++){
        func(i);
    }
}
//游戏内各种判断
function render () {
    if(game.audio){
        onKeyDown = myAudio.getByteDataArray(0) > 200;
        run = myAudio.getByteDataArray(0) > 150;
    }
    man.speedX = 0;
    if((man.x + man.w + 100) > game.width){
        successAudio.play();
        game.success = true;
        console.log("success!")
    }

    //角色死亡
    if(man.y > 600 || crash(man, worm)){
        man.inWorld = false;
        man.alive = false;
    }
    //debug helper
    if(!man.alive){
        deadAudio.play();
        game.stop();
        //console.log("game over!")
    }

    //判断是否落在了桥上
    var onRoad = false, whichRoad = -1;
    for(var i = 0; i < 10; i++){
        var a = road[i].y - man.y - man.h;
        if(road[i].x < (man.x + man.w *.7) && man.x < (road[i].x + road[i].w - man.w *.2)  && a <= 0){
            man.y = road[i].y - man.h;
            onRoad = true;
            whichRoad = i;
        }else{
            //console.log("未跳在桥上");
        }
    }
    man.movement = !onRoad || run;
    //场景是否完毕
    var mapOver = false;
    if(road[9].x <= (game.width + 50 - road[9].w)){
        mapOver = true;
    }

    //人物是否向上运动
    up = man.speedY < 0;

    //游戏x方向的移动
    man.speedX = 0;
    forEach(function(i){
        road[i].speedX = 0;
    });
    if(onKeyDown || run){
        if(man.x <= 400 || mapOver){
            man.speedX = 2;
        }else{
            forEach(function(i){
                road[i].speedX = -2;
            })
        }
    }

    //人物速度y方向
    if(onKeyDown){//按下跳跃键
        if(onRoad) {
            man.gravity = 0;
            man.speedY = 0;
        }else{
            man.gravity += 0.0006;
        }
        if(!jump) {//如果不是跳跃状态
            //跳跃状态为真，获得向上的爆发速度，向右的速度，和向上的加速度
            jump = true;
            jumpAudio.play();
            man.speedY = -2;
            man.gravity = -0.02;
        }
    }else{
        if(onRoad){//在桥上，人物停止，不是跳跃状态
            jump = false;
            man.gravity = 0;
            man.speedY = 0;
        }else{//不在桥上，获得向下的加速度，向右的速度
            man.gravity = 0.04;
        }
    }

    if(whichRoad == 5 && worm.speedX == 0){
        worm.speedX = -2;
        worm.x = road[5].x + road[5].w *.8;
    }
    if(worm.x < (road[5].x - worm.w)){
        worm.speedX = -1;
        worm.gravity = 0.5;
    }

    flag.x = road[9].x + road[9].w - flag.w - 50;

}
var onKeyDown = false;
var run = false;
var jump = false;
var up = false;

var jumpAudio = document.getElementById("jump");
var deadAudio = document.getElementById("dead");
var successAudio = document.getElementById("success");


function getEle(name){
    return document.getElementsByClassName(name)[0];
}
var hint = getEle("hint");
var eleRestart = getEle("restart");
var gameplay = getEle("gameplay");
var have = getEle("have");
var notHave = getEle("notHave");
eleRestart.onclick = function(){
    game.restart();
};
gameplay.onclick = function(){
    game.gamePlay = true;
    game.restart();
};
have.onclick = function(){
    game.audio = true;
    game.restart();
};
notHave.onclick = function(){
    onKeyDown = false;
    game.audio = false;
    game.restart();
};
window.document.onkeydown = function(keyEvent){
    keyEvent = keyEvent ? keyEvent : window.event;
    keyEvent.which = keyEvent.which ? keyEvent.which : keyEvent.keyCode;
    if(keyEvent.which == 13){
        onKeyDown = true;
    }
};
window.document.onkeyup = function(keyEvent){
    keyEvent = keyEvent ? keyEvent : window.event;
    keyEvent.which = keyEvent.which ? keyEvent.which : keyEvent.keyCode;
    if(keyEvent.which == 13){
        onKeyDown = false;
    }
};